package com.hb.znpt.viewmodel;

import android.app.Application;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;

import com.hb.znpt.BuildConfig;
import com.hb.znpt.activity.LeaseActivity;
import com.hb.znpt.activity.LesseeActivity;
import com.hb.znpt.activity.OfflineActivity;
import com.hb.znpt.activity.SelfUseActivity;
import com.hb.znpt.activity.UserInfoAcitivty;
import com.hb.znpt.bean.PersonalBean;
import com.hb.znpt.bean.UpgradeBean;
import com.hb.znpt.model.MainModel;
import com.hb.znpt.utils.Constants;
import com.hb.znpt.utils.ObjectWriter;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.rxjava.rxlife.RxLife;
import com.unitlib.base.base.BaseViewModel;
import com.unitlib.base.utils.SPUtils;
import com.unitlib.base.utils.ToastUtils;
import com.unitlib.base.utils.constant.LiveConstants;

import java.io.File;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import rxhttp.wrapper.param.RxHttp;

/**
 * @Description: 描述
 * @Author: houbing
 * @CreateDate: 2021/9/2 13:55
 */
public class MainViewModel extends BaseViewModel<MainModel> {

    public PersonalBean data;

    private File mApkFile;

    public MutableLiveData<String> quitData = new MutableLiveData<>();

    public MutableLiveData<UpgradeBean> updataData = new MutableLiveData<>();

    public MainViewModel(@NonNull Application application) {
        super(application);
        model = new MainModel();
    }

    @Override
    public void onCreate() {
        mApkFile = new File(context.getExternalFilesDir("down").getAbsoluteFile() + "/" + System.currentTimeMillis() + ".apk");
        data = new PersonalBean();
        model.crops()
                .observeOn(AndroidSchedulers.mainThread())
                .as(RxLife.as(owner))
                .subscribe(bean -> {
                    ObjectWriter.write(context, bean, "nzwlist");
                }, error -> {
                    // 啥也不干
                });
    }

    @Override
    public void onResume() {
        model.info()
                .observeOn(AndroidSchedulers.mainThread())
                .as(RxLife.as(owner))
                .subscribe(bean -> {
                    SPUtils.getInstance().put(Constants.SP_NAME, bean.getXm());
                    SPUtils.getInstance().put(Constants.SP_ZNID, bean.getZnid());
                    data.setBean(bean);
                    data.notifyChange();
                }, error -> {
                    // 啥也不干
                });
        model.upgrade()
                .observeOn(AndroidSchedulers.mainThread())
                .as(RxLife.as(owner))
                .subscribe(bean -> {
                    int vc = Integer.parseInt(bean.getVersion());
                    if (BuildConfig.VERSION_CODE < vc) {
                        updataData.setValue(bean);
                    }
                }, error -> {
                    // 啥也不干
                });
    }

    public void quit(View view) {
        quitData.setValue("");
    }

    public void self(View view) {
        startActivity(SelfUseActivity.class);
    }

    public void lease(View view) {
        startActivity(LeaseActivity.class);
    }

    public void photo(View view) {
        startActivity(LesseeActivity.class);
    }

    public void user(View view) {
        startActivity(UserInfoAcitivty.class);
    }

    public void offline(View view) {
        startActivity(OfflineActivity.class);
    }

    public void download(UpgradeBean bean) {
        mApkFile = new File(context.getExternalFilesDir("down").getAbsoluteFile() + "/" + System.currentTimeMillis() + ".apk");
        RxHttp.get(bean.getUrl())
                .asDownload(mApkFile.getPath(), AndroidSchedulers.mainThread(), progress -> {
                    showDialogMsg("已下载" + progress.getProgress() + "%");
                })
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(disposable -> {
                    showDialog("开始下载...");
                })
                .doFinally(() -> {
                    dismissDialog();
                })
                .as(RxLife.as(owner))
                .subscribe(s -> {
                    installApk();
                }, throwable -> {
                    ToastUtils.showShort("下载失败！");
                });
    }


    private void installApk() {
        XXPermissions.with(context)
                .permission(Permission.REQUEST_INSTALL_PACKAGES)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            Intent intent = new Intent();
                            intent.setAction(Intent.ACTION_VIEW);
                            Uri uri;

                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileprovider", mApkFile);
                                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                            } else {
                                uri = Uri.fromFile(mApkFile);
                            }

                            intent.setDataAndType(uri, "application/vnd.android.package-archive");
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            context.startActivity(intent);
                        } else {
                            ToastUtils.showShort("应用安装权限被禁止，请手动授权限");
                            XXPermissions.startPermissionActivity(context, permissions);
                        }
                    }
                });
    }
}
